require 'login'
require 'miscfunc'
require 'hpricot'
require 'open-uri'

class Kaixin < Login
    include MiscFunc

    def goto_park
        info "redirect to parking game"
        @park_url = 'http://www.kaixin001.com/app/app.php?aid=1040'
        @ie_for_kaixin.goto @park_url
        @valid_cars    = my_cars_status
        @valid_friends = my_friends_status
        @prefer = []
        @nonprefer = []
        @force = 0
    end

    def goto_team
        info "redirect to team game"
        @team_url = 'http://www.kaixin001.com/!parking/myteam.php'
        @ie_for_kaixin.goto @team_url
        @jy_list = []
        @gg_list = []
    end

    def parking
        begin
            do_parking
        rescue => err
            error err
            error "Your password might be wrong!!!"
            raise "PasswordWrong"
        end
      show_money
        finnal_check if @valid_cars.size > 0
    end
    

    def do_post(post_list)
        @ie_for_kaixin.goto @park_url
        info "My parking status"
        park_status = @ie_for_kaixin.document.parentwindow['v_userdata']
        parkings = park_status['parking']
        0.upto(parkings.length - 1) { |i|
            parking = parkings[i.to_s]
            car_uid       = parking['car_uid']
            info "CARUID #{car_uid}"
            parkid        = parking['parkid'].to_s
            car_real_name = parking['car_real_name']
            car_name      = parking['car_name']
            car_profit    = parking['car_profit']
            info "#{car_real_name}'s #{car_name } incoming #{car_profit}"
            if post_list.include?(car_uid)
                info "Post #{car_real_name}'s #{car_name }"
                info "Got money: #{car_profit}"
                @ie_for_kaixin.document.parentWindow.execScript("parking_post(#{parkid})")
                sleep 2
                frame = @ie_for_kaixin.frame(:name, /iframe/)
                frame.button(:index=>1).click
                sleep 1
            end
        }
    end

    def do_oil(jy_list, gg_list)
      Dir.glob(".tmp/*_oil.html").each do |file|
        info "#{file}" 
        oil_doc = open("#{file}") { |aof| Hpricot(aof)}      
        oil_doc.search("a[@class='jy']").each do |n|
          oil_info = n.to_s
          oil_list = oil_info.scan(/\((.*)\)/).to_s.split "," || []
          oiluid = oil_list[0].strip
          teamid = oil_list[1].strip
          if jy_list.include?(oiluid)
            info "script oil(#{oiluid} , #{teamid}, 1)"    
            @ie_for_kaixin.goto @match_url
            sleep 3
            @ie_for_kaixin.document.parentWindow.execScript("oil(#{oiluid} , #{teamid}, 1)")
            sleep 2
            frame = @ie_for_kaixin.frame(:id, "iframe_parent")
            frame.button(:index=>1).click
            sleep 5
          elsif gg_list.include?(oiluid)
            message "do you want gg to #{oiluid}?"
            info "script oil(#{oiluid} , #{teamid}, 0)"    
            @ie_for_kaixin.goto @match_url
            sleep 3
            @ie_for_kaixin.document.parentWindow.execScript("oil(#{oiluid} , #{teamid}, 0)")
            sleep 2
            frame = @ie_for_kaixin.frame(:id, "iframe_parent")
            frame.button(:index=>1).click
            sleep 5
          end
        end
      end
    end

    def show_money
        info "Refreshing the page..."
        @ie_for_kaixin.goto @park_url
        userdata = @ie_for_kaixin.document.parentWindow['v_userdata']
        info "You have cash: #{userdata['user']['cash']}"
    end

    def show_match
      @ie_for_kaixin.goto @team_url
      File.open(".tmp/myteam.html", 'w+b') { |file| file.puts(@ie_for_kaixin.html) }
      info "File myteam.html saved"
      
      team_doc = open(".tmp/myteam.html") { |mtf| Hpricot(mtf)}
      has_own_team = team_doc.search("div[@id='teamlist']").search("img[@src='http://img.kaixin001.com.cn/i2/park/match/ts_1.gif']")

      if (has_own_team == "")
        i = -2
      else
        i = 0            
      end
      team_doc.search("a[@href*=matchDetail]").each do |m|
        match_info = m.to_s 

        if !match_info.index('img') && (i > -2)
          match_list = match_info.scan(/\((.*)\)/).to_s.split "," || []
          matchuid = match_list[0].strip
          matchid = match_list[1].strip
          
          @match_url = "http://www.kaixin001.com/!parking/match.php?matchuid=#{matchuid}&matchid=#{matchid}"

          @ie_for_kaixin.goto @match_url
          if i == -1
            oil_file = ".tmp/my_own.html"
          else
            oil_file = ".tmp/#{matchuid}_oil.html"            
          end
          
          File.open("#{oil_file}", 'w+b') { |file| file.puts(@ie_for_kaixin.html) }
          info "File #{oil_file} saved"

          oil_doc = open("#{oil_file}") { |f| Hpricot(f) }
          match = oil_doc.search("span[@class='c9']").inner_html.scan(/\( (.*)\)/)
          info "#{match}"
          oil_doc.search("div[@class='cd_box']").each do |om|
            
            team = om.search("div[@class='c3 mt5 ml15']/b").inner_html
            temp = om.search("div[@class='cs_s tac']")

            detail = temp.inner_html.split(/<br \/>/) || []
            
            has_run = detail[0]
            status = detail[1]
            speed = detail[2]
            if (speed != "&nbsp;")
              s = ""
              temp.search("img").each do |img|
                s = s + img.to_s.scan(/([\d]).gif/).to_s
              end
            else
              s = "0"
            end
            speed = s
            info "#{team} #{has_run} #{status} speed #{speed}kph" 
          end
        end
        i = i + 1
        sleep 5
      end
    end

    def finnal_check
        info "Still have #{@valid_cars.size} are not moved" 
        @valid_cars.each do |car|
            info car
        end
        info "End of this login"
    end
    
    def reinit_flist(prefer, nonprefer, force)
        info "Processing prefer and nonprefer list"
        @prefer = prefer
        @nonprefer = nonprefer
        @force = force
        
        tmp_hash = Hash.new
        @valid_friends.each do |f|
            key, value = f.split("|", 2)
            tmp_hash.store(key.to_s, value)
        end

        prefer.map! { |f| "#{f}|#{tmp_hash[f]}" }
        nonprefer.map! { |f| "#{f}|#{tmp_hash[f]}" }
        old_friends = @valid_friends
        @valid_friends = @valid_friends - prefer - nonprefer
        @valid_friends = @valid_friends + ( old_friends & prefer ).reverse
        @valid_friends = ( old_friends & nonprefer).reverse + @valid_friends if force == 0
        info @valid_friends
        @valid_friends.uniq!
    end

    def my_cars_status
        info "Show where are my cars"
        valid_cars = []
        userdata = @ie_for_kaixin.document.parentWindow['v_userdata']
        msg = "I have #{userdata['car'].length} cars:\n"
        0.upto(userdata['car'].length - 1) { |i|
            car = userdata["car"][i.to_s]
            v_parkid = car['parkid']
            msg += "#{car['car_name']}(Price: #{car['price'].to_s}) parks at #{car['park_real_name']}'s "
            msg += "#{(v_parkid.to_i >> 16) & 0xff > 0 ? 'Free' : 'Non-Free'} Position, "
            msg += "with incoming #{car['park_profit']}\n"
            valid_cars << "#{car['carid'].to_s}|#{car['park_uid'].to_s}|#{car['car_name']}|#{car['park_real_name']}" if car['park_profit'] > 150
        }
        message msg
        return valid_cars
    end

    def my_friends_status
        info "My Friends status"
        frienddata = @ie_for_kaixin.document.parentWindow['v_frienddata']
        valid_friends = []
        msg = "I have #{frienddata.length.to_s} friends parking area to park my car\n"
        0.upto(frienddata.length-1) do |i|
            friend = frienddata[i.to_s]
            car_status = friend['full'].to_i == 0 ? "Not Full" : "Full"
            status = friend['online'] == 1 ? "Online" : "Offline"
            msg += "#{"%-10s" % [friend['real_name']]}#{"%10s" % ["(#{friend['uid'].to_s})"]} #{status} : "
            msg += "#{car_status}\n"
            valid_friends << "#{friend['uid'].to_s}|#{friend['real_name']}" if friend['full'].to_i == 0
        end
        message msg
        return valid_friends
    end

    def do_parking
        while @valid_friends.size > 0 do
            friend = @valid_friends.pop
            friend_uid, friend_name = friend.split("|")
            cars = @valid_cars.find_all { |c| not_park_at(friend_uid, c) }[0, 4]
            next if cars == []
            debug "#{cars}"
            info "Parking to #{friend_name}'s Park areas"
            park_cars_on(friend_uid, cars)
            return if @valid_cars == 0
            if @valid_cars.size == 1 and @valid_friends.size == 1 then
                if @valid_friends.find { |f| !not_parked_uid(f, park_uid) } then
                    info "Can not park anymore"
                    return
                end
            end
        end
    end

    def park_cars_on(uid, cars)
        info "Update to flash to the park"
        if( uid.length > 1)
            @ie_for_kaixin.document.parentWindow.execScript("gotouser(#{uid})")
        else
            @ie_for_kaixin.document.parentWindow.execScript("gotoneighbor(#{uid})")
        end

        sleep 5
       

        begin
            flashdata = @ie_for_kaixin.document.parentWindow['userdata']
            index = 0
            0.upto(flashdata['parking'].length - 1) do |i|
                carid, park_uid, carname, parkname = cars[index].split "|"
                car = flashdata["parking"][i.to_s]
                next if car['car_uid'] != 0 || (car['parkid'].to_i >> 16) & 0xff > 0

                info "Moving #{carname} #{carid} from #{parkname}"
                if park_car_at(car['parkid'], carid) then
                    @valid_cars.delete_if {|c| c == cars[index] }
                    index = index.succ
                    old_friend = "#{park_uid}|#{parkname}"
                    if @nonprefer.include?(old_friend) then
                        @valid_friends.insert(0, old_friend) if @force == 0
                    else 
                        @valid_friends.push(old_friend)
                    end
                    @valid_friends.uniq!
                    break if index == cars.length
                end
            end

        rescue => err
            error err
            return false
        end
        return true
    end

    def park_car_at(parkid, carid)
        begin
            @ie_for_kaixin.document.parentWindow.execScript("parking_park(#{parkid})")
            sleep 5
            @ie_for_kaixin.frame('iframe_parent').radio(:name, 'car', carid).click
            @ie_for_kaixin.frame('iframe_parent').button(:id, 'btn_sc').click
            sleep 5
        rescue => err
            error err
            return false
        end
        return true
    end

    def not_park_at(friend_uid, car)
        carid, park_uid, tmpvar = car.split "|", 3
        #debug "#{park_uid} and #{friend_uid}"
        #debug "#{friend_uid != park_uid}"
        #debug "#{friend_uid != park_uid}"
        return true if friend_uid != park_uid
        return false
    end

    def not_parked_uid(str, uid)
        id, name  = str.split "|"
        if id != uid then
            return true
        else
            return false
        end
    end
    
end
